<?php

namespace backend\modules\system\controllers;

use backend\controllers\BaseController;
use backend\models\OpenapiShop;
use common\models\BusMember;
use common\models\BusMemberConsume;
use common\models\BusMemberConsumeList;
use common\models\BusService;
use common\models\BusServiceExtend;
use common\models\BusServiceOrder;
use common\models\SysShop;
use yii;
use yii\helpers\Url;

class SiteController extends BaseController
{
    public $layout = '/agent';

    public function init()
    {
        parent::init();
        if ($this->userInfo->user_type == 1) {
            $this->redirect(Url::toRoute('/system/agent/index'));
        } elseif ($this->userInfo->user_type == 2) {
            $this->redirect(Url::toRoute('/agent/bossmanage/list'));
        }
    }

    /**
     * 系统的首页
     * @return string
     */
    public function actionIndex()
    {
        $this->layout = '/agent';

        $startTime = date("Y-m-d") . " 00:00:00";
        $endTime = date("Y-m-") . (date("d") + 1) . " 00:00:00";
        $where = "shop_id = " . $this->userInfo->shop_id . " and " . "consume_time >= '$startTime' and consume_time < '$endTime'";
        $refund_where = $this->where[0] . " and " . "consume_time >= '$startTime' and consume_time < '$endTime'" . " and consume_type = '退款'";
        $bus_service_extend_where = "shop_id = " . $this->userInfo->shop_id . " and " . "add_time >= '$startTime' and add_time < '$endTime' and is_reward = 1";
        $bus_service_where = "shop_id = " . $this->userInfo->shop_id . " and " . "service_endtime >= '$startTime' and service_endtime < '$endTime' and service_status = 2";
        $bus_member_where = "shop_id = " . $this->userInfo->shop_id . " and " . "create_time >= '$startTime' and create_time < '$endTime'";

        $start_month = date("Y-m-01") . " 00:00:00";
        $end_month = date("Y-") . (date("m") + 1) . '-01' . " 00:00:00";
        $member_where = "bus_member_consume.shop_id = " . $this->userInfo->shop_id . " and " . "bus_member_consume.consume_time >= '$start_month' and bus_member_consume.consume_time < '$end_month'";
        $goods_dec_where = "bus_member_consume_list.shop_id = " . $this->userInfo->shop_id . " and " . "bus_member_consume_list.create_time >= '$start_month' and bus_member_consume_list.create_time < '$end_month' and bus_member_consume_list.finance_type=3";
        $bus_member_beautycard_where = "bus_member_consume_list.shop_id = " . $this->userInfo->shop_id . " and " . "bus_member_consume_list.create_time >= '$start_month' and bus_member_consume_list.create_time < '$end_month' and (bus_member_consume_list.finance_type=2 or bus_member_consume_list.finance_type=5 or bus_member_consume_list.finance_type=4)";
        $bus_service_order = "shop_id = " . $this->userInfo->shop_id . " and order_status = 1 and order_time >= '$startTime' and order_time < '$endTime'";
        $bus_service = "shop_id = " . $this->userInfo->shop_id . " and service_status = 3 and make_time >= '$startTime' and make_time < '$endTime'";

        $consumeList = BusMemberConsume::find()
            ->select([
                '(sum(cash_pay) + sum(unionpay)) as consume_amount', // 营业收入
//                'sum(cash_pay) as cash_pay',
//                'sum(unionpay) as unionpay',

            ])
            ->where($where . " and consume_type != '退款'")
            ->asArray()->all();

        // 退款金额
        $refund = BusMemberConsume::find()->select([
            'sum(consume_amount) as consume_amount',
        ])->where($refund_where)->asArray()->all();

        // 最终营业收入
        $consumeList[0]['consume_amount'] = $consumeList[0]['consume_amount'] - $refund[0]['consume_amount'];

        //  消耗金额
        $bus_service_extends = BusServiceExtend::find()->select(["sum(consume_amount) as consume_amount"])->where($bus_service_extend_where)->asArray()->all();

        //  今日到店
        $bus_services = BusService::find()->where($bus_service_where)->asArray()->groupBy("service_member_id")->all();
        $bus_services = count($bus_services);

        // 新增会员
        $bus_members = BusMember::find()->select(["count(member_id) as count_member_id"])->where($bus_member_where)->asArray()->all();
        // app预约
        $bus_service_order = BusServiceOrder::find()->select(["count(order_id) as order_id"])->where($bus_service_order)->asArray()->all();
        // 店铺预约
        $bus_service = BusService::find()->select(["count(service_id) as service_id"])->where($bus_service)->asArray()->all();

        $bus_service_order = $bus_service_order[0]['order_id'] + $bus_service[0]['service_id'];

        // 本月消费最高会员
        $member_pay = BusMember::find()->select([
            'bus_member.member_name',
            'bus_member.member_id',
            '(sum(bus_member_consume.cash_pay) + sum(bus_member_consume.unionpay)) as consume_amount', // 营业收入
        ])
            ->leftJoin("bus_member_consume", "bus_member_consume.member_id = bus_member.member_id")->where($member_where . " and bus_member_consume.consume_type != '退款' and bus_member.del_flag='1'")->groupBy('bus_member.member_id')->orderBy('consume_amount desc')->limit(4)->asArray()->all();

        // 本月热销单品
        $goods_dec = BusMemberConsumeList::find()->select([
            'sum(bus_member_consume_list.count) as dec_count',
            'bus_repertory.repertory_name',
            'bus_repertory.repertory_specs',
            'bus_repertory.repertory_count'
        ])->leftJoin('bus_repertory', 'bus_member_consume_list.relation_id = bus_repertory.repertory_id')
            ->where($goods_dec_where)->limit(4)->groupBy('bus_repertory.repertory_id')->orderBy('dec_count desc')->asArray()->all();

        // 热销服务
        $bus_member_beautycard = BusMemberConsumeList::find()->select([
            'sum(bus_member_consume_list.count) as dec_count',
            'bus_member_consume_list.finance_type',
            'bus_config.*',
        ])->leftJoin('bus_config', 'bus_member_consume_list.relation_id = bus_config.config_id and bus_config.shop_id=' . $this->userInfo->shop_id)
            ->where($bus_member_beautycard_where)->limit(4)->groupBy('bus_config.config_id')->orderBy('dec_count desc')->asArray()->all();
//var_dump($bus_member_beautycard);exit;
        $shop_isopen_online = SysShop::find()->where("shop_id = ". $this->userInfo->shop_id)->asArray()->all();

        $get_url_msg = '';
        if ($shop_isopen_online[0]['isopen_online'] == 1) {
            $get_url_msg = $this->get_shop_online();
        }

        return $this->render("index", [
            'consumeList' => $consumeList,
            'bus_service_extends' => $bus_service_extends,
            'bus_services' => $bus_services,
            'bus_members' => $bus_members,
            'member_pay' => $member_pay,
            'goods_dec' => $goods_dec,
            'bus_member_beautycard' => $bus_member_beautycard,
            'shop_num' => $get_url_msg ? $get_url_msg['result']['count'] : 0,
            'bus_service_order' => $bus_service_order,
            'birthday_count' => \common\models\BusMember::birthday($this->userInfo->shop_id) // 今日过生的会员数
        ]);
    }

    /**
     * 接口调用获取线上店铺7天反问人数
     * @return mixed|string
     */
    public function get_shop_online()
    {
        // api获取线上店铺
        $baseUrl = \Yii::$app->params['baseUrl'];
        $tagUrl = \Yii::$app->params['count'];
        $model = new OpenapiShop();
        $api_data = json_encode(['shop_id' => $this->userInfo->shop_id]);
        $get_url_msg = '';
        try {
            $get_url_msg = $model->get_url_msg($api_data, $baseUrl . $tagUrl);
            $get_url_msg = json_decode($get_url_msg, true);

            if ($get_url_msg['status'] != 10000) {
                $get_url_msg['result']['count'] = 0;
            }
            return $get_url_msg;
        } catch (\Exception $e) {
            // $this->error('访问网络出错！');
        }
    }

    /**
     * 切换分店
     * @date: 2016-2-23
     * @author: futao
     * @param $shopId
     */
    public function actionChangeshop()
    {
        $shopId = \Yii::$app->request->get('shop_id');
        if (!$this->changeShop($shopId)) {
            $this->error('修改失败！');
        }
        $this->redirect(Url::toRoute('/system/site/index'));
    }

    public function actionRevenue()
    {
        $startTime = date("Y-m-d");
        $endTime = date("Y-m-") . (date("d") + 1);
        $where = "shop_id = " . $this->userInfo->shop_id . " and " . "consume_time >= '$startTime' and consume_time < '$endTime'";
        $refund_where = $this->where[0] . " and " . "consume_time >= '$startTime' and consume_time < '$endTime'" . " and consume_type = '退款'";
        $consumeList = BusMemberConsume::find()
            ->select([
                'sum(cash_pay) as cash_pay',
                'sum(unionpay) as unionpay',
                'sum(give_pay) as give_pay',
                'sum(balance_pay) as balance_pay',
                '(sum(cash_pay) + sum(unionpay)) as consume_amount', // 营业收入
            ])
            ->where($where . " and consume_type != '退款'")
            ->asArray()->all();
        //  消耗金额
        $bus_service_extend_where = "shop_id = " . $this->userInfo->shop_id . " and " . "add_time >= '$startTime' and add_time < '$endTime'  and is_reward = 1";
        $bus_service_extends = BusServiceExtend::find()->select(["sum(consume_amount) as consume_amount"])->where($bus_service_extend_where)->asArray()->all();

        // 退款金额
        $refund = BusMemberConsume::find()->select([
            'sum(consume_amount) as consume_amount',
        ])->where($refund_where)->asArray()->all();
        // 最终营业收入
        $consumeList[0]['consume_amount'] = $consumeList[0]['consume_amount'] - $refund[0]['consume_amount'];

        $arr = [
            'cash_pay' => $consumeList[0]['cash_pay'],
            'unionpay' => $consumeList[0]['unionpay'],
            'give_pay' => $consumeList[0]['give_pay'],
            'balance_pay' => $consumeList[0]['balance_pay'],
            'consume_amount' => $consumeList[0]['consume_amount'], // 营业收入
            'consume_amount_extends' => $bus_service_extends[0]['consume_amount'], // 消耗金额
        ];
        echo json_encode($arr);
    }

    /**
     * 本月营收
     */
    public function actionSalemap()
    {
        //  本月
        $day = date("d");
        for ($i = 1; $i <= $day; $i++) {
            $startTime = date("Y-m-" . $i);
            $lastTime = date("Y-m-d", strtotime("$startTime +1 day"));
            $condition = "shop_id = " . $this->userInfo->shop_id . " and " . "consume_time >= '$startTime' and consume_time < '$lastTime'" . " and consume_type != '退款'";
            $consume_amount = BusMemberConsume::find()->select(['(sum(cash_pay) + sum(unionpay)) as consume_amount'])->where($condition)->asArray()->all();

            $refund_where = $this->where[0] . " and " . "consume_time >= '$startTime' and consume_time < '$lastTime'" . " and consume_type = '退款'";
            // 退款金额
            $refund = BusMemberConsume::find()->select([
                'sum(consume_amount) as consume_amount',
            ])->where($refund_where)->asArray()->all();
            // 最终营业收入
            $arr[$i] = $consume_amount[0]['consume_amount'] - $refund[0]['consume_amount'];
        }
        echo json_encode($arr);
    }

    /**
     * 动画
     */
    public function actionAnimation()
    {
        $this->layout = '/alert';
        return $this->render("animation");
    }

}
